﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Server.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class FileUpload : IService
    {
        /// <summary>
        /// 요청받은 메시지의 본문
        /// </summary>
        CCL.SocketMessage.Request.FileUpload m_body;

        /// <summary>
        /// 새로운 서비스를 생성합니다.
        /// </summary>
        /// <param name="body">요청받은 메시지 본문</param>
        public FileUpload(CCL.SocketMessage.Request.FileUpload body)
        {
            m_body = body;
        }

        /// <summary>
        /// 서비스를 시작합니다.
        /// </summary>
        /// <returns>전송할 byte배열</returns>
        public byte[] Execute()
        {
            CCL.SocketMessage.Response.FileUpload fu = null;
            CCL.SocketMessage.Message msg = null;

            SqlConnection sqlCon = null;
            SqlTransaction trans = null;

            try
            {
                string path = m_body.ProjectID + "\\" + m_body.Revision + "\\" + m_body.RelativePath;

                // 데이터베이스에 넣음
                using (sqlCon = new SqlConnection(Properties.Resources.ConnectionString))
                {
                    sqlCon.Open();

                    trans = sqlCon.BeginTransaction();

                    SqlCommand sqlCmd = new SqlCommand(@"
                        INSERT INTO [ProjectFile](projectId, revision, path)
                        VALUES (@pid, @rev, @path)
                    ", sqlCon, trans);

                    sqlCmd.Parameters.AddWithValue("@pid", m_body.ProjectID);
                    sqlCmd.Parameters.AddWithValue("@rev", m_body.Revision);
                    sqlCmd.Parameters.AddWithValue("@path", m_body.RelativePath);

                    sqlCmd.ExecuteNonQuery();

                    // 파일을 생성함
                    CCL.Utility.FileUtility.BytesToFile(m_body.FileBytes, "Project\\" + path);

                    fu = new CCL.SocketMessage.Response.FileUpload();
                    msg = CCL.SocketMessage.Message.MessageResponseBuilder(fu);

                    trans.Commit();

                    sqlCon.Close();
                }
            }
            catch (System.Exception ex)
            {
                if(trans != null)
                    trans.Rollback();

                fu = new CCL.SocketMessage.Response.FileUpload(ex.Message);
                msg = CCL.SocketMessage.Message.MessageResponseBuilder(fu);
            }
            finally
            {
                if (sqlCon != null)
                    sqlCon.Close();
            }

            return msg.GetByte();
        }
    }
}
